package com.hmall.gateway.filter;

import com.hmall.common.exception.UnauthorizedException;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 登录过滤器
 *
 * @author Moozy
 * @since 2025/5/2
 **/
@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    private final JwtTool jwtTool;

    /**
     * 路径匹配判断
     */
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 用户认证校验
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取 request
        ServerHttpRequest request = exchange.getRequest();

        // 判断是否拦截，不需拦截直接放行
        if (isExclude(request.getPath().toString())) {
            return chain.filter(exchange);
        }

        // 获取 token
        String token = null;
        List<String> authTokens = request.getHeaders().get("authorization");
        if (authTokens != null && !authTokens.isEmpty()) {
            token = authTokens.get(0);
        }

        // 校验 token
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (UnauthorizedException e) {
            // 校验不通过，拦截，设置响应状态码 401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // * 通过设置请求头传递用户信息
        String userInfo = userId.toString();
        ServerWebExchange serverWebExchange = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();

        // 放行
        return chain.filter(serverWebExchange);
    }

    /**
     * 判断是否是不需要拦截的请求路径
     *
     * @param path 请求路径
     * @return 判断结果
     */
    private boolean isExclude(String path) {
        for (String excludePathPattern : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePathPattern, path)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 设置过滤器优先级
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
